package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.login

import android.util.Patterns
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.IApiProcessCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.doPostRequest
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.user.mainProcessFormat
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.event.IAnalyticsEvent
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.util.AnalyticsUtil
import org.json.JSONObject

class LoginGhanaViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _loginFormState = MutableLiveData<LoginGhanaFormState>()
    val loginFormState: LiveData<LoginGhanaFormState> = _loginFormState

    private val _loginResult = MutableLiveData<LoginGhanaResult>()
    val loginResult: LiveData<LoginGhanaResult> = _loginResult

    private val _otpResult = MutableLiveData<LoginGhanaResult>()
    val otpResult: LiveData<LoginGhanaResult> = _otpResult

    private val _codeInputState = MutableLiveData<LoginGhanaCodeInputState>()
    val codeInputState: LiveData<LoginGhanaCodeInputState> = _codeInputState

    private val _mainProcessResult = MutableLiveData<LoginGhanaMainProcessResult>()
    val mainProcessResult: LiveData<LoginGhanaMainProcessResult> = _mainProcessResult

    private val _nextRouterResult =
        MutableLiveData<LoginGhanaNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<LoginGhanaNextRouterResult<AppCompatActivity>> =
        _nextRouterResult

    /** 验证码 */
    private val codes = mutableListOf("", "", "", "")

    /** 手机号 */
    var phone = ""

    /** 登录标志 */
    var directLoginFlag = "NO"

    /**
     * 开始登录
     */
    fun startLogin(phone: String) {
        ProjectApplication.mobAction(isGet = false, phone)

        val accList: List<JSONObject> = ProjectApplication.mAccUsers.filter { item ->
            val accM = item.optString("accM")
            accM == phone
        }
        if (accList.isEmpty()) {
            getOtp(phone)
            return
        }

        // 直接登录
        _loadingResult.value = false
        val accUser = accList.first()
        val token = accUser.optString("accTk")
        val userId = accUser.optString("accUid")
        ProjectApplication.tkAction(false, token)
        ProjectApplication.uidAction(false, userId)
        _loginResult.value = LoginGhanaResult(success = true)
    }

    /** 登录接口 */
    fun login() {
        val isCodeErr = this.codes.any {
            it.isBlank()
        }
        if (phone.isBlank() or isCodeErr) {
            _loginResult.value = LoginGhanaResult(error = "Login Error!")
            return
        }

        val code = if (directLoginFlag == "YES") {
            "0000"
        } else {
            this.codes.joinToString("")
        }

        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["mobile"] = phone
        action["code"] = code
        action["notBindWalletFlag"] = "YES"
        action["directLoginFlag"] = directLoginFlag
        action["path"] = "v2H7iAYvbbtja04tuB8FgQ"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val token = obj.optString("token")
                val userId = obj.optString("userId")
                val type = obj.optString("type")
                ProjectApplication.tkAction(false, token)
                ProjectApplication.uidAction(false, userId)
                _loginResult.value = LoginGhanaResult(success = true)

                try {
                    if (type.contains("REGISTER", true)) {
                        AnalyticsUtil.addEvent(IAnalyticsEvent.AT_REGISTER)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _loginResult.value = LoginGhanaResult(error = errMsg)
            }
        })
    }

    // 获取验证码接口
    fun getOtp(phone: String) {
        _loadingResult.value = true
        ProjectApplication.mobAction(isGet = false, phone)

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["mobile"] = phone
        action["path"] = "pDqsV7lR6m3E4BFgTJpkA"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val loginFlag = obj.optString("directLoginFlag")
                if (loginFlag.isNotBlank()) {
                    directLoginFlag = loginFlag
                }
                if (directLoginFlag == "YES") {
                    _otpResult.value = LoginGhanaResult(directFlag = true)
                } else {
                    _otpResult.value = LoginGhanaResult(success = true)
                }
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _otpResult.value = LoginGhanaResult(error = errMsg)
            }
        })
    }

    /** 查询主流程接口 */
    fun mainProcess() {
        _loadingResult.value = true

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj")
                _mainProcessResult.value = LoginGhanaMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _mainProcessResult.value = LoginGhanaMainProcessResult(error = errMsg)
            }
        })
    }

    fun loginPhoneDataChanged(phone: String) {
        if (!isPhoneValid(phone)) {
            _loginFormState.value = LoginGhanaFormState(phoneError = "Not a valid phone number")
        } else {
            this.phone = phone
            _loginFormState.value = LoginGhanaFormState(isDataValid = true)
        }
    }

    fun loginOtpDataChanged(isDel: Boolean = false, code: String) {
        if (isDel) {
            // 删除
            var delIndex = -1
            for (index in (codes.size - 1) downTo 0) {
                if (codes[index].isNotBlank()) {
                    delIndex = index
                    break
                }
            }
            if (delIndex >= 0) {
                codes.removeAt(delIndex)
                _codeInputState.value = LoginGhanaCodeInputState(
                    codes = mutableListOf(
                        codes[0],
                        codes[1],
                        codes[2],
                        codes[3]
                    )
                )
            }
        } else {
            // 增加
            var addIndex = -1
            for (index in 0 until codes.size) {
                if (codes[index].isBlank()) {
                    addIndex = index
                    break
                }
            }
            if (addIndex >= 0) {
                codes[addIndex] = code
                val hasBlank = codes.any {
                    it.isBlank()
                }
                _codeInputState.value = LoginGhanaCodeInputState(
                    done = (!hasBlank),
                    codes = mutableListOf(
                        codes[0],
                        codes[1],
                        codes[2],
                        codes[3]
                    )
                )
            }
        }
    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormat()
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                LoginGhanaNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }

    /**
     * 手机号是否有效
     */
    private fun isPhoneValid(phone: String): Boolean {
        return if (phone.contains('@')) {
            Patterns.EMAIL_ADDRESS.matcher(phone).matches()
        } else {
            phone.length >= 9
        }
    }
}